import { ref, inject } from 'vue'
import type { ApplicationIframeSDKManager } from '@/plugins/iframeSDKManager/iframeSDKManager.d'
import { IframeSDKEventMap } from '@/plugins/iframeSDKManager/events'
import { parseTagKeyBord } from '@/utils'
import useSceneDataStore from '@/stores/scene'

const {
  TAG_CLICK,
  TAG_HOVER_IN,
  TAG_CLICK_START,
  WORK_LOADED,
  MODEL_SWITCH_BEFORE,
  MODEL_SWITCH_COMPLETE,
  TAG_ALL_LOADED
} = IframeSDKEventMap

export function useIframeEvents() {
  const iframeSDKManager = inject('iframeSDKManager') as ApplicationIframeSDKManager
  const sceneDataStore = useSceneDataStore()
  const coverLoading = ref(false)

  const {
    setAllTagList,
    setCurrentSceneId,
    setCurrentModelType,
    setCurrentCameraMode,
    setCurrentClickTagId,
    setBusinessParams
  } = sceneDataStore

  // 标签点击开始处理
  const handleTagClickStart = (data: any) => {
    console.error('tag.click.start', JSON.stringify(data))
    setCurrentClickTagId(data.id)

    const keybordObject = parseTagKeyBord(data.keyword)
    const { type, building_id, project_id } = keybordObject as any

    setBusinessParams({ type, building_id, project_id })
  }

  // 标签点击处理
  const createTagClickHandler = (callbacks: {
    onBuildingClick?: (params: { project_id: string; building_id: string }) => Promise<void>
    onPanelHeightChange?: (height: number) => void
  }) => {
    return async (data: any) => {
      setCurrentClickTagId(data.id)

      const { currentClickTagData } = sceneDataStore
      const keybordObject = parseTagKeyBord(currentClickTagData?.keyword)
      console.warn('>>>>点击了标签，提取参数>>>>>>>', currentClickTagData?.keyword, keybordObject)

      const { type, building_id, project_id } = keybordObject as any
      const businessParams = { type, building_id, project_id }

      setBusinessParams(businessParams)

      if (type === 'building' && callbacks.onBuildingClick) {
        await callbacks.onBuildingClick({ project_id, building_id })

        if (callbacks.onPanelHeightChange) {
          callbacks.onPanelHeightChange(Math.round(0.45 * window.innerHeight))
        }
      }
    }
  }

  // 模型切换处理
  const handleModelSwitchBefore = (data: any) => {
    coverLoading.value = true
    console.error('model.switch.before', data)

    setCurrentModelType(data.type)
    setCurrentCameraMode(data.mode)
    setCurrentSceneId(data.sceneId)
  }

  // 模型切换完成处理器函数
  const createModelSwitchCompleteHandler = (callbacks: {
    onDataFetch?: (params: { project_id: string }) => Promise<void>
  }) => {
    return async (data: any) => {
      setCurrentSceneId(data.sceneId)

      try {
        const { businessParams } = sceneDataStore
        const { project_id } = businessParams

        if (callbacks.onDataFetch) {
          await callbacks.onDataFetch({ project_id })
        }
      } catch (error) {
        console.error('模型切换完成处理失败:', error)
      } finally {
        coverLoading.value = false
      }
    }
  }

  // 标签悬停处理
  const handleTagHoverIn = (data: any) => {
    console.error('标签悬停触发事件', data)
  }

  // 作品加载完成处理
  const handleWorkLoaded = (currentSceneData: any) => {
    setCurrentModelType(currentSceneData.type)
    setCurrentCameraMode(currentSceneData.mode)
    setCurrentSceneId(currentSceneData.sceneId)
  }

  // 标签全部加载完成处理
  const createTagAllLoadedHandler = (callbacks: {
    onInitialDataFetch?: (projectId: string) => Promise<void>
    onTagsProcessed?: () => void
    onComplete?: () => void
  }) => {
    return async () => {
      const { project_id } = sceneDataStore.businessParams

      if (callbacks.onInitialDataFetch) {
        await callbacks.onInitialDataFetch(project_id as string)
      }

      try {
        if (!sceneDataStore.allTagList || sceneDataStore.allTagList.length === 0) {
          const allTagList = await iframeSDKManager.getTags()
          setAllTagList(allTagList)

          if (callbacks.onTagsProcessed) {
            callbacks.onTagsProcessed()
          }
        }
      } catch (error) {
        console.error('获取tags失败:', error)
      } finally {
        if (callbacks.onComplete) {
          callbacks.onComplete()
        }
      }
    }
  }

  return {
    iframeSDKManager,
    coverLoading,
    handleTagClickStart,
    createTagClickHandler,
    handleModelSwitchBefore,
    createModelSwitchCompleteHandler,
    handleTagHoverIn,
    handleWorkLoaded,
    createTagAllLoadedHandler,

    eventTypes: {
      TAG_CLICK,
      TAG_HOVER_IN,
      TAG_CLICK_START,
      WORK_LOADED,
      MODEL_SWITCH_BEFORE,
      MODEL_SWITCH_COMPLETE,
      TAG_ALL_LOADED
    }
  }
}
